package com.newworld.dmsapp2.register;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.HouseManageListActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.bean.RelationType;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class RegisterDishostActivity extends BaseActivity implements
		OnClickListener, OnCheckedChangeListener {
	private LinearLayout ly_intent;
	private Button btn_dishost_next;
	private EditText ownerNameEdtTxt;
	private TextView reg_text_remaininfo;
	private RadioGroup relationTypeRdoGop;
	// 验证信息在20字内
	private EditText noteEdtTxt;// 定义一个文本输入框
	private ProgressBar progressBar;
	private View timeline_view_2;
	private ImageView timeline_3stage_image_3;
	private TextView timeline_text_3;
	
	private List<RelationType> relationTypeList = new ArrayList<RelationType>();
	private List<RelationType> relationTypeExceptHost = new ArrayList<RelationType>();
	
	private Intent intent;
	protected String ownername;
	private String ownerphone;
	private String postscript = "";
	private String houseId;

	protected String flag;
	protected String response;
	protected String message = "登录失败";
	protected RelationType relationtype;// 关系类型(亲戚，家人，租户)的id
	private int num = 20;// 限制的最大字数
	private String sessionId;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register_dishost);
		initData();
		initViews();
		initEvents();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void initData(){
		User user = SingleSample.getInstance(this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	protected void initViews() {
		setTitlebarLeft(this, Config.TITLE_HOUSE_ATTATCH,
				HouseProvingActivity.class);

		ly_intent = (LinearLayout) findViewById(R.id.reg_dishost_intent);
		btn_dishost_next = (Button) findViewById(R.id.reg_dishost_btn);
		ownerNameEdtTxt = (EditText) findViewById(R.id.reg_dishost_hostname);
		noteEdtTxt = (EditText) findViewById(R.id.reg_dishost_note);
		relationTypeRdoGop = (RadioGroup) findViewById(R.id.radioGroup);
		reg_text_remaininfo = (TextView) findViewById(R.id.reg_text_remaininfo);
		timeline_view_2 = (View) findViewById(R.id.timeline_view_2);
		timeline_3stage_image_3 = (ImageView) findViewById(R.id.timeline_3stage_image_3);
		timeline_text_3 = (TextView) findViewById(R.id.timeline_text_3);
		// hasnumTV.setText(num+"");
		progressBar = (ProgressBar) findViewById(R.id.proBar_get_data);
		if (UserMessageActivity.INTENT_FLAG == 1) {
			timeline_view_2.setVisibility(View.GONE);
			timeline_3stage_image_3.setVisibility(View.GONE);
			timeline_text_3.setVisibility(View.GONE);
			btn_dishost_next.setText("关联");
		}
		intent = getIntent();
		if (intent != null) {
			houseId = intent.getStringExtra("houseID");
			relationTypeList = (List<RelationType>) intent
					.getSerializableExtra("relationTypeList");

		}

		for (int i = 0; i < relationTypeList.size(); i++) {
			if (!relationTypeList.get(i).getTypeCode().equals("owner")) {
				relationTypeExceptHost.add(relationTypeList.get(i));
				System.out.println("i------类型"+i);
			}
		}
		for (int i = 0; i < relationTypeExceptHost.size(); i++) {

			RadioButton radioButton = new RadioButton(
					RegisterDishostActivity.this);
			if (i == 0) {
				radioButton.setChecked(true);
				relationtype = relationTypeExceptHost.get(i);
			}
			radioButton.setId(i);
			radioButton.setText(relationTypeExceptHost.get(i).getTypeName());
			// 字体大小20sp
			radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
			radioButton.setTextColor(getResources().getColor(
					R.color.nw_tx_black));
			radioButton.setPadding(0, 0, 6, 0);
			relationTypeRdoGop.addView(radioButton);
			System.out.println("i------非户主类型"+i);

		}

		// 加上字数监听器
		noteEdtTxt.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				temp = s;
			}

			@Override
			public void afterTextChanged(Editable s) {
				int number = num - s.length();
				reg_text_remaininfo.setText(number + "");
				selectionStart = noteEdtTxt.getSelectionStart();
				selectionEnd = noteEdtTxt.getSelectionEnd();
				if (temp.length() > num) {
					s.delete(selectionStart - 1, selectionEnd);
					int tempSelection = selectionEnd;
					noteEdtTxt.setText(s);
					noteEdtTxt.setSelection(tempSelection);// 设置光标在最后
				}
			}

		});

	}

	@Override
	protected void initEvents() {
		ly_intent.setOnClickListener(this);
		btn_dishost_next.setOnClickListener(this);
		// ownerNameEdtTxt.setOnFocusChangeListener(this);
		relationTypeRdoGop.setOnCheckedChangeListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 跳到户主按钮
		case R.id.reg_dishost_intent:
			finish();
			break;
		// 下一步按钮
		case R.id.reg_dishost_btn:

			if ((ownerNameEdtTxt.getText() + "").trim().equals("")) {
				Toast.makeText(RegisterDishostActivity.this, "户主姓名不能为空",
						Toast.LENGTH_SHORT).show();
			} else {
				if (UserMessageActivity.INTENT_FLAG == 0) {
					nonHostRegisterIn();
				} else if (UserMessageActivity.INTENT_FLAG == 1) {
					nonHostRelate();

				}
			}

			break;

		default:
			break;
		}
	}

	/**
	 * 
	 * 非户主关联
	 * 
	 * @param view
	 */
	private void nonHostRelate() {
		// TODO Auto-generated method stub
		ownername = ownerNameEdtTxt.getText().toString();
		postscript = noteEdtTxt.getText().toString();
		System.out.println("postscript----111>"+postscript);
		if (ownername.length() == 0) {
			showShortToast("户主名不能为空");
		} else {

			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					if (Tool.isNetworkAvailable(RegisterDishostActivity.this)) {
						progressBar.setVisibility(android.view.View.VISIBLE);
					} else {
						Toast.makeText(RegisterDishostActivity.this,
								"请检查网络连接！", Toast.LENGTH_SHORT).show();
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if (Tool.isNetworkAvailable(RegisterDishostActivity.this)) {
						try {

							Map<String, String> map = new HashMap<String, String>();
							map.put("functionCode", "houseRelateComplete");
							map.put("relationTypeCode",
									relationtype.getTypeCode());
							map.put("postscript", postscript);
							map.put("ownerName", ownername);
							map.put("houseId", houseId);
							String result = HttpUtil.postRequestSe(Config.RELATE_URL, map,sessionId);
							Log.e("非户主关联result", result);

							message = new JSONObject(result)
									.getString("message");
							flag = new JSONObject(result).getString("flag");

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(RegisterDishostActivity.this, message,
							Toast.LENGTH_SHORT).show();
					if (flag.equals("success")) {

						Intent intent = new Intent(
								RegisterDishostActivity.this,
								HouseManageListActivity.class);

						startActivity(intent);
						finish();
					}

				}
			}.execute(null, null, null);
		}
	}

	/**
	 * 
	 * 非户主点击注册
	 * 
	 * @param view
	 */
	public void nonHostRegisterIn() {

		ownername = ownerNameEdtTxt.getText().toString();
		postscript = noteEdtTxt.getText().toString();
		if (ownername.length() == 0) {
			showShortToast("户主名不能为空");
		} else {

			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					if (Tool.isNetworkAvailable(RegisterDishostActivity.this)) {
						progressBar.setVisibility(android.view.View.VISIBLE);
					} else {
						Toast.makeText(RegisterDishostActivity.this,
								"请检查网络连接！", Toast.LENGTH_SHORT).show();
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if (Tool.isNetworkAvailable(RegisterDishostActivity.this)) {
						try {

							Map<String, String> map = new HashMap<String, String>();
							map.put("ownerName", ownername);
							map.put("ownerPhone", ownerphone);
							map.put("houseId", houseId);
							map.put("postscript", postscript);
							map.put("relationTypeId", relationtype.getId());
							String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL, Config.CONFIRM_OWNERNAME)
									, map,sessionId);
							Log.e("非户主信息验证result", result);

							message = new JSONObject(result)
									.getString("message");
							flag = new JSONObject(result).getString("flag");

						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(RegisterDishostActivity.this, message,
							Toast.LENGTH_SHORT).show();
					if (flag.equals("success")) {

						Intent intent = new Intent(
								RegisterDishostActivity.this,
								UserMessageActivity.class);

						intent.putExtra("houseID", houseId);
						System.out.println("houseID" + houseId);
						intent.putExtra("ownername", ownername);
						intent.putExtra("postscript", postscript);
						intent.putExtra("relationtypeid", relationtype.getId());
						startActivity(intent);
					}

				}
			}.execute(null, null, null);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			Intent intent = new Intent(RegisterDishostActivity.this,
					HouseProvingActivity.class);
			intent.putExtra("houseID", houseId);
			System.out.println("houseID" + houseId);
			intent.putExtra("ownername", ownername);
			intent.putExtra("ownerphone", ownerphone);
			intent.putExtra("relationtypeid", relationtype.getId());
			startActivity(intent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		relationtype = relationTypeExceptHost.get(checkedId);

		System.out.println("relationTypeExceptHost"
				+ relationTypeExceptHost.get(checkedId));
	}
}
